package weaver.tools.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

/**
 * @Title: Ecology9
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2021-09-15
 * @Description: 公共工具类
 * @ModifyLog:
 **/

public class CommUtil {

    /**
     *@Description: 判断数组中是否包含某个字符串
     */
    public static boolean containsStringArray(String[] array, String target) {
        return Arrays.asList(array).contains(target);
    }

    /**
     *@Description:  获取UUID(大写)
     */
    public String getUUIDStr() {
        String uuid = UUID.randomUUID().toString().toUpperCase();
        return uuid.replace("-", "");
    }

    /**
     *@Description: 获取uuid截取16位
     */
    public String getUUID16Str() {
        String uuid = UUID.randomUUID().toString();
        return uuid.replace("-", "").substring(0, 16);
    }

    /**
     *@Description: 判断是否是json数组格式
     */
    public boolean isJSONArray(String fieldvalue) {
        boolean flag = false;
        if (!(fieldvalue.trim().equals(""))) {
            try {
                JSONArray.parseArray(fieldvalue);
                flag = true;
            } catch (Exception e) {
                flag = false;
            }
        }
        return flag;
    }

    /**
     *@Description: 判断是否是json格式
     */
    public static boolean isJSONObject(String str) {
        boolean flag = true;
        try {
            JSONObject.parseObject(str);
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     *@Description: 去除html标签
     */
    public static String removeHtml(String str) {
        StringBuilder temp = new StringBuilder();
        while (str.contains("<")) {
            int index = str.indexOf("<");
            temp.append(str.substring(0, index));
            str = str.substring(index + 1);
            index = str.indexOf(">");
            str = str.substring(index + 1);
        }
        temp.append(str);
        Pattern p = compile("\\s*|\t|\r|\n");
        Matcher m = p.matcher(temp.toString());
        temp = new StringBuilder(m.replaceAll(""));
        return temp.toString();
    }

    /*
     *@Description: 生成长度为length的范围为0~number的整数随机验证码
     */
    public static String generateRandomNum(int number, int length) {
        int[] a = new int[length];
        Random r = new Random();
        a[0] = r.nextInt(length);
        for (int i = 1; i < length; i++) {
            //数组存入个数
            a[i] = r.nextInt(number);
            for (int j = 0; j < i; j++) {
                if (a[j] == a[i]) {
                    i--;
                    break;
                }
            }
        }
        // 遍历
        StringBuilder str = new StringBuilder();
        for (int s : a) {
            str.append(s);
        }
        return str.toString();
    }

    /*
     *@Description: 不够位数的在前面补0，保留num的长度位数字
     */
    public static String autoGenericCode(String code, int num) {
        String result = "";
        result = String.format("%0" + num + "d", Integer.parseInt(code));
        return result;
    }

    /*
     *@Description: 随机范围A~Z生成四位字母不重复的字符串
     */
    public static String genrateStr(int count) {
        String[] source = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I",
                "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z"};
        StringBuilder stringBuilder = new StringBuilder(count);
        int len = source.length;
        for (int i = 0; i < count; i++) {
            final int index = new Random().nextInt(len);
            stringBuilder.append(source[index]);
        }
        return stringBuilder.toString();
    }

    /**
     *@Description: JSON对象转的xml字符串格式化
     */
    public static String jsonToPrettyXml(JSONObject json) throws IOException, SAXException {
        Document document = jsonToDocument(json);
        /* 格式化xml */
        OutputFormat format = OutputFormat.createPrettyPrint();
        // 设置缩进为4个空格
        format.setIndent(" ");
        format.setIndentSize(4);

        StringWriter formatXml = new StringWriter();
        XMLWriter writer = new XMLWriter(formatXml, format);
        writer.write(document);
        return formatXml.toString();
    }

    /**
     *@Description: JSON对象转Document对象
     */
    public static Document jsonToDocument(JSONObject json) throws SAXException {
        Document document = DocumentHelper.createDocument();
        document.setXMLEncoding("UFT-8");

        // root对象只能有一个
        for (Object rootKey : json.keySet()) {
            Element root = jsonToElement(json.getJSONObject((String) rootKey), (String) rootKey);
            document.add(root);
            break;
        }
        return document;
    }

    /**
     *@Description: JSON对象转Element对象
     */
    public static Element jsonToElement(JSONObject json, String nodeName) {
        Element node = DocumentHelper.createElement(nodeName);
        for (Object key : json.keySet()) {
            Object child = json.get(key);
            if (child instanceof JSONObject) {
                node.add(jsonToElement(json.getJSONObject((String) key), (String) key));
            } else {
                Element element = DocumentHelper.createElement((String) key);
                element.setText(json.getString((String) key));
                node.add(element);
            }
        }

        return node;
    }

}
